<template>
  <div class="ai-assistant-layout">
    <!-- AI助手头像 -->
    <div
      class="ai-avatar"
      :class="{ active: isAssistantActive, listening: isListening }"
      @click="toggleAssistant"
    >
      <div class="avatar-container">
        <div class="avatar-icon">
          <el-icon v-if="!isListening" :size="28"><Service /></el-icon>
          <div v-else class="listening-animation">
            <div class="wave wave1"></div>
            <div class="wave wave2"></div>
            <div class="wave wave3"></div>
          </div>
        </div>
        <div class="status-indicator" :class="assistantStatus"></div>
      </div>
      <div class="avatar-name">AI助手</div>
    </div>

    <!-- AI对话面板 -->
    <transition name="chat-panel">
      <div v-if="showChatPanel" class="chat-panel" :style="chatPanelStyle">
        <div class="chat-header">
          <div class="header-info">
            <div class="assistant-info">
              <div class="info-avatar">
                <el-icon :size="20"><Service /></el-icon>
              </div>
              <div class="info-text">
                <div class="info-name">AI助手</div>
                <div class="info-status">{{ assistantStatusText }}</div>
              </div>
            </div>
          </div>
          <div class="header-actions">
            <button class="action-btn" @click="clearChat">
              <el-icon><Delete /></el-icon>
            </button>
            <button class="action-btn" @click="closeChatPanel">
              <el-icon><Close /></el-icon>
            </button>
          </div>
        </div>

        <div class="chat-messages" ref="chatMessagesRef">
          <div
            v-for="(message, index) in chatMessages"
            :key="index"
            class="message"
            :class="{ 'user-message': message.type === 'user', 'assistant-message': message.type === 'assistant' }"
          >
            <div class="message-avatar" v-if="message.type === 'assistant'">
              <el-icon><Service /></el-icon>
            </div>
            <div class="message-content">
              <div class="message-text">{{ message.text }}</div>
              <div class="message-time">{{ formatTime(message.timestamp) }}</div>
              <div v-if="message.actions" class="message-actions">
                <button
                  v-for="action in message.actions"
                  :key="action.text"
                  class="action-button"
                  @click="handleMessageAction(action)"
                >
                  {{ action.text }}
                </button>
              </div>
            </div>
          </div>
          
          <!-- 输入提示 -->
          <div v-if="isTyping" class="message assistant-message typing">
            <div class="message-avatar">
              <el-icon><Service /></el-icon>
            </div>
            <div class="message-content">
              <div class="typing-indicator">
                <span></span>
                <span></span>
                <span></span>
              </div>
            </div>
          </div>
        </div>

        <div class="chat-input">
          <div class="input-container">
            <el-input
              v-model="inputMessage"
              placeholder="输入您的问题或需求..."
              @keyup.enter="sendMessage"
              :disabled="isProcessing"
              ref="chatInput"
            >
              <template #suffix>
                <button
                  class="send-btn"
                  @click="sendMessage"
                  :disabled="!inputMessage.trim() || isProcessing"
                >
                  <el-icon><Promotion /></el-icon>
                </button>
              </template>
            </el-input>
          </div>
          <div class="input-actions">
            <el-tooltip
              :content="isRecognitionSupported ? '语音导航' : '当前浏览器不支持语音识别'"
              placement="top"
            >
              <button
                class="voice-btn"
                :class="{ active: isListening, disabled: !isRecognitionSupported }"
                :disabled="!isRecognitionSupported"
                @click="toggleVoiceInput"
              >
                <el-icon><Microphone /></el-icon>
              </button>
            </el-tooltip>
            <el-tooltip content="快速操作" placement="top">
              <button class="quick-btn" @click="showQuickActions">
                <el-icon><More /></el-icon>
              </button>
            </el-tooltip>
          </div>
        </div>
      </div>
    </transition>

    <!-- 快速操作面板 -->
    <transition name="quick-actions">
      <div v-if="showQuickActionsPanel" class="quick-actions-panel">
        <div class="panel-header">
          <h3>快速操作</h3>
          <button class="close-btn" @click="closeQuickActions">
            <el-icon><Close /></el-icon>
          </button>
        </div>
        <div class="actions-grid">
          <div
            v-for="action in quickActions"
            :key="action.id"
            class="action-card"
            @click="executeQuickAction(action)"
          >
            <div class="action-icon" :style="{ background: action.color }">
              <el-icon :size="24">
                <component :is="action.icon" />
              </el-icon>
            </div>
            <div class="action-info">
              <div class="action-title">{{ action.title }}</div>
              <div class="action-desc">{{ action.description }}</div>
            </div>
          </div>
        </div>
      </div>
    </transition>

    <!-- 主内容区 -->
    <main class="main-content">
      <!-- 智能导航栏 -->
      <div class="smart-navbar">
        <div class="nav-left">
          <div class="breadcrumb-container">
            <el-breadcrumb separator="/">
              <el-breadcrumb-item
                v-for="(item, index) in smartBreadcrumbs"
                :key="index"
                :to="item.path"
              >
                {{ item.title }}
              </el-breadcrumb-item>
            </el-breadcrumb>
          </div>
        </div>
        <div class="nav-right">
          <div class="smart-search">
            <el-input
              v-model="globalSearch"
              placeholder="智能搜索..."
              size="small"
              clearable
              @input="handleSmartSearch"
            >
              <template #prefix>
                <el-icon><Search /></el-icon>
              </template>
              <template #suffix>
                <div class="search-suggestions" v-if="searchSuggestions.length > 0">
                  <div
                    v-for="suggestion in searchSuggestions"
                    :key="suggestion.path"
                    class="suggestion-item"
                    @click="navigateToSuggestion(suggestion)"
                  >
                    <el-icon><component :is="suggestion.icon" /></el-icon>
                    <span>{{ suggestion.title }}</span>
                  </div>
                </div>
              </template>
            </el-input>
          </div>
          <button class="nav-btn" @click="showNavigationSettings">
            <el-icon><Setting /></el-icon>
          </button>
        </div>
      </div>

      <!-- 页面内容 -->
      <div class="page-content">
        <router-view v-slot="{ Component }">
          <transition name="page-fade" mode="out-in">
            <component :is="Component" :key="$route.fullPath" />
          </transition>
        </router-view>
        
        <!-- AI助手欢迎提示 -->
        <div v-if="!hasUserInteracted" class="ai-welcome-tip">
          <div class="welcome-content">
            <div class="welcome-icon">
              <el-icon :size="48"><Service /></el-icon>
            </div>
            <h2>欢迎使用AI助手模式</h2>
            <p v-if="isRecognitionSupported">
              点击右下角的AI助手头像开始智能对话，支持<strong>语音导航</strong>功能
            </p>
            <p v-else>
              点击右下角的AI助手头像开始智能对话
            </p>
            <div class="welcome-features">
              <div class="feature-item">
                <el-icon><ChatDotRound /></el-icon>
                <span>智能对话</span>
              </div>
              <div class="feature-item" :class="{ highlight: isRecognitionSupported }">
                <el-icon><Microphone /></el-icon>
                <span>语音导航</span>
                <el-tag v-if="isRecognitionSupported" type="success" size="small">可用</el-tag>
              </div>
              <div class="feature-item">
                <el-icon><MagicStick /></el-icon>
                <span>智能分析</span>
              </div>
            </div>
            <div v-if="isRecognitionSupported" class="voice-example">
              <div class="example-title">💡 试试语音命令：</div>
              <div class="example-commands">
                <el-tag>打开销售管理</el-tag>
                <el-tag>打开库存管理</el-tag>
                <el-tag>打开财务管理</el-tag>
              </div>
            </div>
            <button class="start-btn" @click="startWithAI">
              开始使用AI助手
            </button>
          </div>
        </div>
      </div>
    </main>

    <!-- 上下文菜单 -->
    <div
      v-if="showContextMenuPanel"
      class="context-menu"
      :style="contextMenuStyle"
      @click.stop
    >
      <div class="menu-item" @click="askAI('帮我分析当前页面的数据')">
        <el-icon><TrendCharts /></el-icon>
        <span>数据分析</span>
      </div>
      <div class="menu-item" @click="askAI('帮我优化这个页面的操作流程')">
        <el-icon><MagicStick /></el-icon>
        <span>流程优化</span>
      </div>
      <div class="menu-item" @click="askAI('生成这个页面的使用说明')">
        <el-icon><Document /></el-icon>
        <span>使用说明</span>
      </div>
      <div class="menu-divider"></div>
      <div class="menu-item" @click="showHelpDialog">
        <el-icon><QuestionFilled /></el-icon>
        <span>帮助中心</span>
      </div>
    </div>

    <!-- 遮罩层 -->
    <div
      v-if="showContextMenuPanel"
      class="context-overlay"
      @click="closeContextMenu"
    ></div>

    <!-- 语音识别状态 -->
    <transition name="voice-panel">
      <div v-if="isListening" class="voice-recognition">
        <div class="voice-panel">
          <div class="voice-animation">
            <div class="voice-wave"></div>
            <div class="voice-wave"></div>
            <div class="voice-wave"></div>
            <div class="voice-wave"></div>
            <div class="voice-wave"></div>
          </div>
          <div class="voice-text">{{ voiceText || '请说出您要打开的页面...' }}</div>
          <div class="voice-hint">支持语音命令：打开销售管理、打开库存管理等</div>
          <el-button type="danger" size="small" @click="stopVoiceRecognition" style="margin-top: 12px">
            <el-icon><Close /></el-icon>
            停止识别
          </el-button>
        </div>
      </div>
    </transition>

    <!-- AI帮助对话框 -->
    <el-dialog
      v-model="showHelpDialog"
      title="AI助手使用指南"
      width="600px"
      :close-on-click-modal="false"
    >
      <div class="ai-help-content">
        <div class="help-section">
          <h4>🎯 智能功能</h4>
          <ul>
            <li><strong>语音导航</strong>：点击麦克风按钮，说出"打开xxx"即可跳转页面</li>
            <li><strong>语音交互</strong>：支持中文语音识别，实时转文字</li>
            <li><strong>智能搜索</strong>：输入关键词获得智能建议</li>
            <li><strong>数据分析</strong>：右键菜单快速分析页面数据</li>
            <li><strong>流程优化</strong>：AI自动分析并提供优化建议</li>
          </ul>
        </div>
        <div class="help-section">
          <h4>💡 语音导航命令</h4>
          <ul>
            <li>说"打开销售管理"或"帮我打开销售"快速跳转</li>
            <li>说"打开库存管理"或"库存"跳转到库存</li>
            <li>说"打开财务管理"或"财务"跳转到财务</li>
            <li>说"打开项目管理"或"项目"跳转到项目</li>
            <li>支持16个模块的语音导航，识别准确率高</li>
          </ul>
        </div>
        <div class="help-section">
          <h4>🔧 使用技巧</h4>
          <ul>
            <li>点击AI头像打开对话面板</li>
            <li>点击麦克风按钮开始语音识别</li>
            <li>语音识别会自动搜索并跳转到匹配的页面</li>
            <li>如果未匹配到页面，会作为普通对话处理</li>
            <li>使用Chrome或Edge浏览器获得最佳体验</li>
          </ul>
        </div>
      </div>
      <template #footer>
        <el-button @click="showHelpDialog = false">关闭</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, onUnmounted, nextTick, markRaw } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { ElMessage } from 'element-plus'
import {
  Service, Delete, Close, Promotion, Microphone, More, ArrowRight,
  Search, Setting, TrendCharts, MagicStick, Document, QuestionFilled,
  HomeFilled, ShoppingCart, Box, Money, UserFilled, DataBoard,
  Calendar, Bell, Star, Share, ChatDotRound
} from '@element-plus/icons-vue'
import { menuData } from '@/config/menu'

const router = useRouter()
const route = useRoute()

// 状态管理
const isAssistantActive = ref(false)
const showChatPanel = ref(false)
const isListening = ref(false)
const hasUserInteracted = ref(false)
const isProcessing = ref(false)
const isTyping = ref(false)
const inputMessage = ref('')
const chatMessages = ref([])
const chatInput = ref(null)
const chatMessagesRef = ref(null)

// 快速操作
const showQuickActionsPanel = ref(false)

// 搜索功能
const globalSearch = ref('')
const searchSuggestions = ref([])

// 上下文菜单
const showContextMenuPanel = ref(false)
const contextMenuStyle = ref({})
const showHelpDialog = ref(false)

// 语音识别
const voiceText = ref('')
const recognition = ref(null)
const isRecognitionSupported = ref(false)

// 计算属性
const assistantStatus = computed(() => {
  if (isListening.value) return 'listening'
  if (isProcessing.value) return 'processing'
  if (isAssistantActive.value) return 'active'
  return 'idle'
})

const assistantStatusText = computed(() => {
  switch (assistantStatus.value) {
    case 'listening': return '正在聆听...'
    case 'processing': return '正在思考...'
    case 'active': return '在线'
    default: return '待机中'
  }
})

const smartBreadcrumbs = computed(() => {
  const matched = route.matched.filter(item => item.meta && item.meta.title)
  return matched.map(item => ({
    path: item.path,
    title: item.meta.title
  }))
})

const chatPanelStyle = computed(() => ({
  right: '20px',
  bottom: '100px',
  width: '400px',
  height: '600px'
}))

// 快速操作配置
const quickActions = computed(() => [
  {
    id: 'navigate-dashboard',
    title: '返回首页',
    description: '快速回到数据概览',
    icon: markRaw(HomeFilled),
    color: '#409eff',
    action: () => router.push('/dashboard')
  },
  {
    id: 'analyze-data',
    title: '数据分析',
    description: '分析当前页面数据',
    icon: markRaw(TrendCharts),
    color: '#67c23a',
    action: () => askAI('帮我分析当前页面的数据')
  },
  {
    id: 'optimize-workflow',
    title: '流程优化',
    description: '优化当前操作流程',
    icon: markRaw(MagicStick),
    color: '#e6a23c',
    action: () => askAI('帮我优化这个页面的操作流程')
  },
  {
    id: 'generate-report',
    title: '生成报告',
    description: '生成当前页面报告',
    icon: markRaw(Document),
    color: '#f56c6c',
    action: () => askAI('帮我生成这个页面的使用报告')
  },
  {
    id: 'undeveloped-stats',
    title: '开发中功能',
    description: `查看访问记录（${undevelopedFeatures.value.length}）`,
    icon: markRaw(Star),
    color: '#ff6b6b',
    action: () => showDevelopmentRoadmap(),
    show: undevelopedFeatures.value.length > 0
  },
  {
    id: 'schedule-meeting',
    title: '安排会议',
    description: '安排相关会议',
    icon: markRaw(Calendar),
    color: '#909399',
    action: () => askAI('帮我安排一个关于当前页面的会议')
  },
  {
    id: 'set-reminder',
    title: '设置提醒',
    description: '设置重要事项提醒',
    icon: markRaw(Bell),
    color: '#9c27b0',
    action: () => askAI('帮我设置一个关于当前页面的提醒')
  }
].filter(action => action.show !== false))

// 方法
const toggleAssistant = () => {
  showChatPanel.value = !showChatPanel.value
  hasUserInteracted.value = true
  if (showChatPanel.value) {
    isAssistantActive.value = true
    nextTick(() => {
      if (chatInput.value) {
        chatInput.value.focus()
      }
    })
  }
}

const startWithAI = () => {
  hasUserInteracted.value = true
  toggleAssistant()
}

const closeChatPanel = () => {
  showChatPanel.value = false
  isAssistantActive.value = false
}

const sendMessage = async () => {
  if (!inputMessage.value.trim() || isProcessing.value) return

  const userMessage = {
    type: 'user',
    text: inputMessage.value,
    timestamp: Date.now()
  }
  
  chatMessages.value.push(userMessage)
  const currentMessage = inputMessage.value
  inputMessage.value = ''
  
  // 显示AI正在输入
  isTyping.value = true
  isProcessing.value = true
  
  // 模拟AI响应
  setTimeout(() => {
    isTyping.value = false
    const response = generateAIResponse(currentMessage)
    chatMessages.value.push(response)
    scrollToBottom()
    isProcessing.value = false
  }, 1500)
}

const generateAIResponse = (message) => {
  const responses = {
    '你好': {
      text: '您好！我是您的AI助手，可以帮助您导航、分析数据、优化流程等。有什么我可以帮助您的吗？',
      actions: [
        { text: '数据分析', action: 'analyze-data' },
        { text: '流程优化', action: 'optimize-workflow' }
      ]
    },
    '帮我打开销售管理': {
      text: '好的，我为您打开销售管理页面。',
      actions: [{ text: '立即打开', action: 'navigate-sales' }]
    },
    '分析数据': {
      text: '我来为您分析当前页面的数据。根据您的访问模式，我建议关注以下几个指标...',
      actions: [
        { text: '查看详细分析', action: 'view-analysis' },
        { text: '生成报告', action: 'generate-report' }
      ]
    }
  }
  
  const response = responses[message] || {
    text: `我理解您想了解"${message}"。让我为您提供相关信息和建议。`,
    actions: [
      { text: '了解更多', action: 'learn-more' },
      { text: '相关功能', action: 'related-features' }
    ]
  }
  
  return {
    type: 'assistant',
    text: response.text,
    timestamp: Date.now(),
    actions: response.actions
  }
}

const handleMessageAction = (action) => {
  switch (action.action) {
    case 'navigate-sales':
      router.push('/sales')
      break
    case 'analyze-data':
      askAI('帮我分析当前页面的数据')
      break
    case 'optimize-workflow':
      askAI('帮我优化这个页面的操作流程')
      break
    case 'try-voice':
      toggleVoiceInput()
      break
    case 'show-commands':
      showSupportedCommands()
      break
    case 'start-using':
      // 已移除智能建议功能
      break
    case 'show-help':
      showHelpDialog.value = true
      break
    case 'view-roadmap':
      showDevelopmentRoadmap()
      break
    case 'recommend-features':
      recommendAlternativeFeatures()
      break
    case 'clear-records':
      clearUndevelopedRecords()
      break
    case 'export-records':
      exportUndevelopedRecords()
      break
    default:
      ElMessage.info(`执行操作: ${action.text}`)
  }
}

// 清除开发中功能记录
const clearUndevelopedRecords = () => {
  undevelopedFeatures.value = []
  saveUndevelopedFeatures()
  
  chatMessages.value.push({
    type: 'assistant',
    text: '已清除所有开发中功能的访问记录。',
    timestamp: Date.now()
  })
  
  scrollToBottom()
  ElMessage.success('记录已清除')
}

// 导出开发中功能记录
const exportUndevelopedRecords = () => {
  if (undevelopedFeatures.value.length === 0) {
    ElMessage.warning('暂无记录可导出')
    return
  }
  
  const data = {
    exportTime: new Date().toISOString(),
    totalFeatures: undevelopedFeatures.value.length,
    totalAccess: undevelopedFeatures.value.reduce((sum, f) => sum + f.count, 0),
    features: undevelopedFeatures.value.map(f => ({
      功能名称: f.title,
      访问路径: f.path,
      访问次数: f.count,
      首次访问: f.timestamp,
      最后访问: f.lastAccess,
      最后命令: f.lastCommand
    }))
  }
  
  const jsonStr = JSON.stringify(data, null, 2)
  const blob = new Blob([jsonStr], { type: 'application/json' })
  const url = URL.createObjectURL(blob)
  const a = document.createElement('a')
  a.href = url
  a.download = `开发中功能访问记录_${new Date().toISOString().split('T')[0]}.json`
  a.click()
  URL.revokeObjectURL(url)
  
  chatMessages.value.push({
    type: 'assistant',
    text: '已导出开发中功能访问记录为JSON文件，您可以将其提交给开发团队。',
    timestamp: Date.now()
  })
  
  scrollToBottom()
  ElMessage.success('记录已导出')
}

// 显示开发计划
const showDevelopmentRoadmap = () => {
  closeQuickActions()
  
  if (undevelopedFeatures.value.length === 0) {
    chatMessages.value.push({
      type: 'assistant',
      text: '目前还没有访问开发中功能的记录。您可以尝试说"打开生产管理"、"打开质量管理"等命令来体验功能检测。',
      timestamp: Date.now()
    })
  } else {
    const stats = undevelopedFeatures.value
      .sort((a, b) => b.count - a.count)
      .map((f, i) => {
        const lastTime = new Date(f.lastAccess).toLocaleString('zh-CN')
        return `${i + 1}. ${f.title}\n   访问次数：${f.count}次\n   最后访问：${lastTime}\n   语音命令："${f.lastCommand}"`
      })
      .join('\n\n')
    
    chatMessages.value.push({
      type: 'assistant',
      text: `📊 开发中功能访问统计：\n\n${stats}\n\n这些功能需求已记录，开发团队会根据访问频率优先开发最需要的功能。`,
      timestamp: Date.now(),
      actions: [
        { text: '清除记录', action: 'clear-records' },
        { text: '导出记录', action: 'export-records' }
      ]
    })
  }
  
  scrollToBottom()
}

// 推荐替代功能
const recommendAlternativeFeatures = () => {
  const availableFeatures = menuItems.value
    .filter(m => m.available)
    .slice(0, 5)
    .map(m => m.title)
    .join('、')
  
  chatMessages.value.push({
    type: 'assistant',
    text: `以下功能已经可以使用：${availableFeatures}等。您可以试试这些功能。`,
    timestamp: Date.now()
  })
  
  scrollToBottom()
}

// 显示支持的语音命令
const showSupportedCommands = () => {
  const availableCommands = menuItems.value
    .filter(item => item.available)
    .map(item => `• ${item.keywords.slice(0, 2).join('、')}`)
    .join('\n')
  
  const developingCommands = menuItems.value
    .filter(item => !item.available)
    .map(item => `• ${item.keywords.slice(0, 2).join('、')}`)
    .join('\n')
  
  let text = `✅ 可用的语音命令：\n\n${availableCommands}\n\n`
  
  if (developingCommands) {
    text += `🔧 开发中的功能：\n\n${developingCommands}\n\n`
  }
  
  text += `您可以说"打开xxx"或"帮我打开xxx"等方式进行导航。`
  
  chatMessages.value.push({
    type: 'assistant',
    text: text,
    timestamp: Date.now()
  })
  
  scrollToBottom()
}

const askAI = (question) => {
  if (!showChatPanel.value) {
    toggleAssistant()
  }
  
  setTimeout(() => {
    inputMessage.value = question
    sendMessage()
  }, 300)
}

// 从系统公共菜单生成语音导航菜单项
const generateMenuItemsFromMenuData = () => {
  const items = []
  
  // 处理主菜单和子菜单
  menuData.forEach(menu => {
    // 生成主菜单的关键词
    const mainKeywords = generateKeywords(menu.title, menu.path)
    
    // 如果有子菜单，添加主菜单项（使用第一个子菜单的路径，如果没有则使用主路径）
    const mainPath = menu.children && menu.children.length > 0 
      ? menu.children[0].path 
      : menu.path
    
    items.push({
      keywords: mainKeywords,
      path: mainPath,
      title: menu.title,
      available: true
    })
    
    // 添加所有子菜单项
    if (menu.children && menu.children.length > 0) {
      menu.children.forEach(child => {
        // 跳过第一个子菜单（已经在主菜单中处理）
        if (child.path !== mainPath) {
          const childKeywords = generateKeywords(child.title, child.path)
          items.push({
            keywords: childKeywords,
            path: child.path,
            title: child.title,
            available: true
          })
        }
      })
    }
  })
  
  return items
}

// 生成关键词数组
const generateKeywords = (title, path) => {
  const keywords = []
  
  // 添加完整标题（保持原样，因为中文搜索需要）
  keywords.push(title.toLowerCase())
  
  // 从标题提取核心词
  const titleParts = title.split(/[管理|中心|平台|系统|设计器|助手]/)
  titleParts.forEach(part => {
    if (part && part.trim()) {
      const trimmed = part.trim().toLowerCase()
      if (trimmed && !keywords.includes(trimmed)) {
        keywords.push(trimmed)
      }
    }
  })
  
  // 从标题生成常见关键词变体
  if (title.includes('管理')) {
    const without = title.replace('管理', '').toLowerCase()
    if (without && !keywords.includes(without)) {
      keywords.push(without)
    }
  }
  if (title.includes('中心')) {
    const without = title.replace('中心', '').toLowerCase()
    if (without && !keywords.includes(without)) {
      keywords.push(without)
    }
  }
  if (title.includes('平台')) {
    const without = title.replace('平台', '').toLowerCase()
    if (without && !keywords.includes(without)) {
      keywords.push(without)
    }
  }
  
  // 从路径提取关键词
  const pathParts = path.replace(/^\//, '').split('/')
  pathParts.forEach(part => {
    if (part && part !== 'list' && part !== 'index' && part !== 'detail') {
      const lowerPart = part.toLowerCase()
      if (!keywords.includes(lowerPart)) {
        keywords.push(lowerPart)
      }
    }
  })
  
  // 添加完整路径（去除开头的斜杠）
  const pathWithoutSlash = path.replace(/^\//, '').toLowerCase()
  if (pathWithoutSlash && !keywords.includes(pathWithoutSlash)) {
    keywords.push(pathWithoutSlash)
  }
  
  // 去重并返回
  return [...new Set(keywords)]
}

// 所有可用的菜单项（用于语音导航）
const menuItems = computed(() => generateMenuItemsFromMenuData())

// 记录访问的开发中功能
const undevelopedFeatures = ref([])

// 保存到localStorage
const saveUndevelopedFeatures = () => {
  try {
    localStorage.setItem('ai_undeveloped_features', JSON.stringify(undevelopedFeatures.value))
  } catch (error) {
    console.error('保存开发中功能记录失败:', error)
  }
}

// 从localStorage加载
const loadUndevelopedFeatures = () => {
  try {
    const saved = localStorage.getItem('ai_undeveloped_features')
    if (saved) {
      undevelopedFeatures.value = JSON.parse(saved)
    }
  } catch (error) {
    console.error('加载开发中功能记录失败:', error)
  }
}

// 搜索匹配菜单
const searchMenu = (text) => {
  const searchText = text.toLowerCase().trim()
  
  // 查找匹配的菜单项
  for (const menu of menuItems.value) {
    for (const keyword of menu.keywords) {
      if (searchText.includes(keyword)) {
        return menu
      }
    }
  }
  
  return null
}

// 记录开发中功能
const recordUndevelopedFeature = (menu, voiceCommand) => {
  const record = {
    title: menu.title,
    path: menu.path,
    voiceCommand: voiceCommand,
    timestamp: new Date().toISOString(),
    count: 1
  }
  
  // 检查是否已记录过
  const existingIndex = undevelopedFeatures.value.findIndex(f => f.path === menu.path)
  
  if (existingIndex > -1) {
    // 已存在，增加访问次数
    undevelopedFeatures.value[existingIndex].count++
    undevelopedFeatures.value[existingIndex].lastAccess = record.timestamp
    undevelopedFeatures.value[existingIndex].lastCommand = voiceCommand
  } else {
    // 新记录
    undevelopedFeatures.value.push({
      ...record,
      lastAccess: record.timestamp,
      lastCommand: voiceCommand
    })
  }
  
  // 保存到localStorage
  saveUndevelopedFeatures()
  
  console.log('记录开发中功能:', {
    功能名称: menu.title,
    访问路径: menu.path,
    语音命令: voiceCommand,
    访问次数: existingIndex > -1 ? undevelopedFeatures.value[existingIndex].count : 1,
    访问时间: record.timestamp
  })
}

// 获取开发中功能统计
const getUndevelopedStats = () => {
  if (undevelopedFeatures.value.length === 0) {
    return '暂无记录'
  }
  
  const stats = undevelopedFeatures.value
    .sort((a, b) => b.count - a.count)
    .slice(0, 5)
    .map((f, i) => `${i + 1}. ${f.title}（访问${f.count}次）`)
    .join('\n')
  
  return `最常访问的开发中功能：\n\n${stats}\n\n我已记录这些需求，感谢您的反馈！`
}

const toggleVoiceInput = () => {
  if (!isRecognitionSupported.value) {
    ElMessage.warning('您的浏览器不支持语音识别功能')
    return
  }
  
  isListening.value = !isListening.value
  if (isListening.value) {
    startVoiceRecognition()
  } else {
    stopVoiceRecognition()
  }
}

const startVoiceRecognition = () => {
  if (!recognition.value) return
  
  voiceText.value = '正在聆听...'
  
  try {
    recognition.value.start()
  } catch (error) {
    console.error('语音识别启动失败:', error)
    ElMessage.error('语音识别启动失败')
    isListening.value = false
    voiceText.value = ''
  }
}

const stopVoiceRecognition = () => {
  if (recognition.value) {
    recognition.value.stop()
  }
  voiceText.value = ''
}

// 初始化语音识别
const initVoiceRecognition = () => {
  // 检查浏览器是否支持语音识别
  const SpeechRecognition = window.SpeechRecognition || window.webkitSpeechRecognition
  
  if (!SpeechRecognition) {
    console.warn('当前浏览器不支持语音识别')
    isRecognitionSupported.value = false
    return
  }
  
  isRecognitionSupported.value = true
  recognition.value = new SpeechRecognition()
  
  // 配置语音识别
  recognition.value.lang = 'zh-CN' // 中文识别
  recognition.value.continuous = false // 单次识别
  recognition.value.interimResults = true // 显示临时结果
  
  // 识别结果回调
  recognition.value.onresult = (event) => {
    const result = event.results[event.results.length - 1]
    const transcript = result[0].transcript
    
    if (result.isFinal) {
      // 最终结果
      voiceText.value = transcript
      isListening.value = false
      
      // 搜索匹配的菜单
      const matchedMenu = searchMenu(transcript)
      
      if (matchedMenu) {
        // 找到匹配的菜单，检查是否可访问
        setTimeout(() => {
          voiceText.value = ''
          
          // 添加用户消息
          chatMessages.value.push({
            type: 'user',
            text: transcript,
            timestamp: Date.now()
          })
          
          // 检查功能是否可用
          if (matchedMenu.available) {
            // 功能可用，执行跳转
            chatMessages.value.push({
              type: 'assistant',
              text: `好的，我为您打开"${matchedMenu.title}"页面。`,
              timestamp: Date.now()
            })
            
            scrollToBottom()
            
            // 跳转页面
            setTimeout(() => {
              router.push(matchedMenu.path)
              ElMessage.success(`已为您打开 ${matchedMenu.title}`)
            }, 500)
          } else {
            // 功能正在开发中
            chatMessages.value.push({
              type: 'assistant',
              text: `抱歉，"${matchedMenu.title}"功能正在开发中，暂时无法访问。我已经记录了您的需求，开发团队会优先完成该功能。`,
              timestamp: Date.now(),
              actions: [
                { text: '查看开发计划', action: 'view-roadmap' },
                { text: '推荐其他功能', action: 'recommend-features' }
              ]
            })
            
            // 记录该功能
            recordUndevelopedFeature(matchedMenu, transcript)
            
            scrollToBottom()
            ElMessage.warning(`${matchedMenu.title} 功能正在开发中`)
          }
        }, 1000)
      } else {
        // 未找到匹配的菜单
        setTimeout(() => {
          inputMessage.value = transcript
          voiceText.value = ''
          sendMessage()
        }, 1000)
      }
    } else {
      // 临时结果（实时显示）
      voiceText.value = transcript
    }
  }
  
  // 识别错误回调
  recognition.value.onerror = (event) => {
    console.error('语音识别错误:', event.error)
    isListening.value = false
    voiceText.value = ''
    
    const errorMessages = {
      'no-speech': '未检测到语音，请重试',
      'audio-capture': '无法访问麦克风，请检查权限',
      'not-allowed': '麦克风权限被拒绝',
      'network': '网络错误，请检查网络连接'
    }
    
    const message = errorMessages[event.error] || '语音识别失败，请重试'
    ElMessage.error(message)
  }
  
  // 识别结束回调
  recognition.value.onend = () => {
    isListening.value = false
    if (!voiceText.value) {
      voiceText.value = ''
    }
  }
}

const clearChat = () => {
  chatMessages.value = []
  ElMessage.success('对话记录已清空')
}

const showQuickActions = () => {
  showQuickActionsPanel.value = !showQuickActionsPanel.value
}

const closeQuickActions = () => {
  showQuickActionsPanel.value = false
}

const executeQuickAction = (action) => {
  action.action()
  closeQuickActions()
}

const handleSmartSearch = () => {
  if (!globalSearch.value) {
    searchSuggestions.value = []
    return
  }
  
  const allItems = [
    { path: '/dashboard', title: '数据概览', icon: markRaw(HomeFilled) },
    { path: '/sales', title: '销售管理', icon: markRaw(ShoppingCart) },
    { path: '/inventory', title: '库存管理', icon: markRaw(Box) },
    { path: '/finance', title: '财务管理', icon: markRaw(Money) },
    { path: '/member', title: '会员管理', icon: markRaw(UserFilled) },
    { path: '/reports', title: '报表中心', icon: markRaw(DataBoard) }
  ]
  
  searchSuggestions.value = allItems.filter(item =>
    item.title.toLowerCase().includes(globalSearch.value.toLowerCase())
  ).slice(0, 5)
}

const navigateToSuggestion = (suggestion) => {
  router.push(suggestion.path)
  globalSearch.value = ''
  searchSuggestions.value = []
}

const showNavigationSettings = () => {
  window.dispatchEvent(new CustomEvent('show-navigation-settings'))
}

const showContextMenu = (e) => {
  showContextMenuPanel.value = true
  contextMenuStyle.value = {
    left: (e?.clientX || 100) + 'px',
    top: (e?.clientY || 100) + 'px'
  }
}

const closeContextMenu = () => {
  showContextMenuPanel.value = false
}

const scrollToBottom = () => {
  nextTick(() => {
    if (chatMessagesRef.value) {
      chatMessagesRef.value.scrollTop = chatMessagesRef.value.scrollHeight
    }
  })
}

const formatTime = (timestamp) => {
  return new Date(timestamp).toLocaleTimeString('zh-CN', {
    hour: '2-digit',
    minute: '2-digit'
  })
}

// 生命周期
onMounted(() => {
  // 加载开发中功能记录
  loadUndevelopedFeatures()
  
  // 初始化语音识别
  initVoiceRecognition()
  
  // 初始化欢迎消息
  chatMessages.value.push({
    type: 'assistant',
    text: isRecognitionSupported.value 
      ? '您好！我是您的AI助手，支持语音导航功能。您可以说"打开销售管理"、"打开库存管理"等命令，我会自动为您跳转到相应页面。'
      : '您好！我是您的AI助手，随时为您提供智能导航、数据分析和工作流程优化服务。',
    timestamp: Date.now(),
    actions: isRecognitionSupported.value ? [
      { text: '试试语音导航', action: 'try-voice' },
      { text: '查看支持的命令', action: 'show-commands' }
    ] : [
      { text: '开始使用', action: 'start-using' },
      { text: '查看帮助', action: 'show-help' }
    ]
  })
  
  // 如果有开发中功能记录，显示提示
  if (undevelopedFeatures.value.length > 0) {
    console.log('开发中功能访问记录：', undevelopedFeatures.value)
  }
})

onUnmounted(() => {
  // 清理语音识别资源
  if (recognition.value) {
    recognition.value.stop()
    recognition.value = null
  }
})
</script>

<style scoped>
.ai-assistant-layout {
  width: 100%;
  height: 100vh;
  position: relative;
  background: #f5f7fa;
  overflow: hidden;
}

/* AI助手头像 */
.ai-avatar {
  position: fixed;
  bottom: 30px;
  right: 30px;
  width: 80px;
  height: 80px;
  cursor: pointer;
  z-index: 1000;
  transition: all 0.3s ease;
}

.ai-avatar:hover {
  transform: scale(1.1);
}

.avatar-container {
  position: relative;
  width: 60px;
  height: 60px;
  margin: 0 auto;
}

.avatar-icon {
  width: 60px;
  height: 60px;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  color: white;
  box-shadow: 0 8px 24px rgba(102, 126, 234, 0.4);
  transition: all 0.3s ease;
}

.ai-avatar.active .avatar-icon {
  background: linear-gradient(135deg, #764ba2 0%, #667eea 100%);
  box-shadow: 0 12px 32px rgba(102, 126, 234, 0.6);
}

.ai-avatar.listening .avatar-icon {
  animation: pulse 1.5s infinite;
}

.status-indicator {
  position: absolute;
  bottom: 2px;
  right: 2px;
  width: 16px;
  height: 16px;
  border-radius: 50%;
  border: 2px solid white;
}

.status-indicator.idle {
  background: #909399;
}

.status-indicator.active {
  background: #67c23a;
}

.status-indicator.listening {
  background: #e6a23c;
  animation: pulse 1s infinite;
}

.status-indicator.processing {
  background: #409eff;
  animation: spin 1s linear infinite;
}

.listening-animation {
  position: relative;
  width: 100%;
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
}

.wave {
  position: absolute;
  width: 4px;
  height: 20px;
  background: white;
  border-radius: 2px;
  animation: wave 1s ease-in-out infinite;
}

.wave1 { animation-delay: 0s; }
.wave2 { animation-delay: 0.2s; }
.wave3 { animation-delay: 0.4s; }

@keyframes wave {
  0%, 100% { height: 10px; }
  50% { height: 30px; }
}

@keyframes pulse {
  0%, 100% { transform: scale(1); }
  50% { transform: scale(1.1); }
}

@keyframes spin {
  from { transform: rotate(0deg); }
  to { transform: rotate(360deg); }
}

.avatar-name {
  text-align: center;
  font-size: 12px;
  color: #606266;
  margin-top: 4px;
  font-weight: 500;
}

/* 对话面板 */
.chat-panel {
  position: fixed;
  background: white;
  border-radius: 12px;
  box-shadow: 0 20px 60px rgba(0, 0, 0, 0.15);
  border: 1px solid rgba(255, 255, 255, 0.2);
  overflow: hidden;
  z-index: 1500;
  display: flex;
  flex-direction: column;
}

.chat-header {
  height: 60px;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 0 16px;
  color: white;
}

.assistant-info {
  display: flex;
  align-items: center;
  gap: 12px;
}

.info-avatar {
  width: 32px;
  height: 32px;
  background: rgba(255, 255, 255, 0.2);
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
}

.info-name {
  font-size: 16px;
  font-weight: 600;
}

.info-status {
  font-size: 12px;
  opacity: 0.8;
}

.header-actions {
  display: flex;
  gap: 8px;
}

.action-btn {
  width: 28px;
  height: 28px;
  border: none;
  background: rgba(255, 255, 255, 0.2);
  color: white;
  border-radius: 4px;
  cursor: pointer;
  display: flex;
  align-items: center;
  justify-content: center;
  transition: all 0.2s ease;
}

.action-btn:hover {
  background: rgba(255, 255, 255, 0.3);
}

.chat-messages {
  flex: 1;
  overflow-y: auto;
  padding: 16px;
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.message {
  display: flex;
  gap: 8px;
  align-items: flex-start;
}

.user-message {
  flex-direction: row-reverse;
}

.message-avatar {
  width: 32px;
  height: 32px;
  background: #f0f2f5;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  color: #606266;
  flex-shrink: 0;
}

.user-message .message-avatar {
  background: #409eff;
  color: white;
}

.message-content {
  max-width: 70%;
}

.user-message .message-content {
  text-align: right;
}

.message-text {
  background: #f0f2f5;
  padding: 8px 12px;
  border-radius: 12px;
  font-size: 14px;
  line-height: 1.4;
  word-wrap: break-word;
}

.user-message .message-text {
  background: #409eff;
  color: white;
}

.message-time {
  font-size: 11px;
  color: #909399;
  margin-top: 4px;
}

.message-actions {
  margin-top: 8px;
  display: flex;
  flex-wrap: wrap;
  gap: 4px;
}

.action-button {
  padding: 4px 8px;
  background: #f0f2f5;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  font-size: 12px;
  cursor: pointer;
  transition: all 0.2s ease;
}

.action-button:hover {
  background: #e4e7ed;
}

.typing {
  opacity: 0.7;
}

.typing-indicator {
  display: flex;
  gap: 4px;
  align-items: center;
}

.typing-indicator span {
  width: 6px;
  height: 6px;
  background: #409eff;
  border-radius: 50%;
  animation: typing 1.4s infinite ease-in-out;
}

.typing-indicator span:nth-child(1) { animation-delay: -0.32s; }
.typing-indicator span:nth-child(2) { animation-delay: -0.16s; }

@keyframes typing {
  0%, 80%, 100% { transform: scale(0.8); opacity: 0.5; }
  40% { transform: scale(1); opacity: 1; }
}

.chat-input {
  padding: 16px;
  border-top: 1px solid #e4e7ed;
  background: #fafafa;
}

.input-container {
  margin-bottom: 8px;
}

.send-btn {
  border: none;
  background: transparent;
  color: #409eff;
  cursor: pointer;
  padding: 4px;
  border-radius: 4px;
  transition: all 0.2s ease;
}

.send-btn:hover {
  background: #f0f2f5;
}

.send-btn:disabled {
  color: #c0c4cc;
  cursor: not-allowed;
}

.input-actions {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.voice-btn {
  width: 32px;
  height: 32px;
  border: none;
  background: #f0f2f5;
  border-radius: 50%;
  cursor: pointer;
  display: flex;
  align-items: center;
  justify-content: center;
  color: #606266;
  transition: all 0.2s ease;
}

.voice-btn:hover {
  background: #e4e7ed;
}

.voice-btn.active {
  background: #f56c6c;
  color: white;
  animation: pulse 1s infinite;
}

.voice-btn.disabled {
  opacity: 0.5;
  cursor: not-allowed;
}

.voice-btn:disabled {
  opacity: 0.5;
  cursor: not-allowed;
}

.quick-btn {
  width: 32px;
  height: 32px;
  border: none;
  background: #f0f2f5;
  border-radius: 50%;
  cursor: pointer;
  display: flex;
  align-items: center;
  justify-content: center;
  color: #606266;
  transition: all 0.2s ease;
}

.quick-btn:hover {
  background: #e4e7ed;
}

/* 快速操作面板 */
.quick-actions-panel {
  position: fixed;
  bottom: 120px;
  right: 30px;
  width: 300px;
  background: white;
  border-radius: 12px;
  box-shadow: 0 20px 60px rgba(0, 0, 0, 0.15);
  z-index: 1400;
  overflow: hidden;
}

.panel-header {
  height: 50px;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 0 16px;
  color: white;
}

.panel-header h3 {
  margin: 0;
  font-size: 16px;
  font-weight: 600;
}

.close-btn {
  width: 24px;
  height: 24px;
  border: none;
  background: rgba(255, 255, 255, 0.2);
  color: white;
  border-radius: 4px;
  cursor: pointer;
  display: flex;
  align-items: center;
  justify-content: center;
}

.actions-grid {
  padding: 16px;
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.action-card {
  display: flex;
  align-items: center;
  padding: 12px;
  border-radius: 8px;
  cursor: pointer;
  transition: all 0.2s ease;
  gap: 12px;
}

.action-card:hover {
  background: #f5f7fa;
  transform: translateY(-2px);
}

.action-icon {
  width: 40px;
  height: 40px;
  border-radius: 8px;
  display: flex;
  align-items: center;
  justify-content: center;
  color: white;
}

.action-info {
  flex: 1;
}

.action-title {
  font-size: 14px;
  font-weight: 500;
  color: #303133;
  margin-bottom: 2px;
}

.action-desc {
  font-size: 12px;
  color: #909399;
}

/* 主内容区 */
.main-content {
  width: 100%;
  height: 100vh;
  display: flex;
  flex-direction: column;
}

.smart-navbar {
  height: 60px;
  background: white;
  border-bottom: 1px solid #e4e7ed;
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 0 24px;
}

.nav-left {
  flex: 1;
}

.breadcrumb-container {
  max-width: 400px;
}

.nav-right {
  display: flex;
  align-items: center;
  gap: 12px;
}

.smart-search {
  position: relative;
  width: 300px;
}

.search-suggestions {
  position: absolute;
  top: 100%;
  left: 0;
  right: 0;
  background: white;
  border: 1px solid #e4e7ed;
  border-top: none;
  border-radius: 0 0 6px 6px;
  max-height: 200px;
  overflow-y: auto;
  z-index: 1000;
}

.search-suggestions .suggestion-item {
  padding: 8px 12px;
  border-bottom: 1px solid #f0f2f5;
  display: flex;
  align-items: center;
  gap: 8px;
  cursor: pointer;
}

.search-suggestions .suggestion-item:hover {
  background: #f5f7fa;
}

.search-suggestions .suggestion-item:last-child {
  border-bottom: none;
}

.nav-btn {
  width: 36px;
  height: 36px;
  border: none;
  background: #f5f7fa;
  border-radius: 6px;
  cursor: pointer;
  display: flex;
  align-items: center;
  justify-content: center;
  color: #606266;
  transition: all 0.2s ease;
}

.nav-btn:hover {
  background: #e4e7ed;
  color: #303133;
}

.page-content {
  flex: 1;
  overflow-y: auto;
  padding: 24px;
  position: relative;
}

/* AI助手欢迎提示 */
.ai-welcome-tip {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  display: flex;
  align-items: center;
  justify-content: center;
  background: linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%);
  z-index: 10;
}

.welcome-content {
  text-align: center;
  max-width: 500px;
  padding: 40px;
  background: white;
  border-radius: 16px;
  box-shadow: 0 20px 60px rgba(0, 0, 0, 0.1);
  border: 1px solid rgba(255, 255, 255, 0.2);
}

.welcome-icon {
  margin-bottom: 24px;
  color: #409eff;
}

.welcome-content h2 {
  margin: 0 0 16px 0;
  font-size: 28px;
  font-weight: 600;
  color: #303133;
}

.welcome-content p {
  margin: 0 0 32px 0;
  font-size: 16px;
  color: #606266;
  line-height: 1.6;
}

.welcome-features {
  display: flex;
  justify-content: center;
  gap: 32px;
  margin-bottom: 32px;
}

.feature-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 8px;
  color: #606266;
  font-size: 14px;
}

.feature-item .el-icon {
  font-size: 24px;
  color: #409eff;
}

.feature-item.highlight {
  color: #67c23a;
}

.feature-item.highlight .el-icon {
  color: #67c23a;
}

.voice-example {
  margin: 24px 0;
  padding: 16px;
  background: #f5f7fa;
  border-radius: 8px;
  border: 1px solid #e4e7ed;
}

.example-title {
  font-size: 14px;
  font-weight: 500;
  color: #606266;
  margin-bottom: 12px;
}

.example-commands {
  display: flex;
  justify-content: center;
  gap: 8px;
  flex-wrap: wrap;
}

.example-commands .el-tag {
  cursor: default;
}

.start-btn {
  padding: 12px 32px;
  background: linear-gradient(135deg, #409eff 0%, #66b1ff 100%);
  color: white;
  border: none;
  border-radius: 8px;
  font-size: 16px;
  font-weight: 500;
  cursor: pointer;
  transition: all 0.3s ease;
  box-shadow: 0 4px 12px rgba(64, 158, 255, 0.3);
}

.start-btn:hover {
  transform: translateY(-2px);
  box-shadow: 0 6px 20px rgba(64, 158, 255, 0.4);
}

/* 上下文菜单 */
.context-menu {
  position: fixed;
  background: white;
  border-radius: 8px;
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.15);
  border: 1px solid #e4e7ed;
  z-index: 2000;
  min-width: 160px;
  overflow: hidden;
}

.menu-item {
  display: flex;
  align-items: center;
  padding: 12px 16px;
  cursor: pointer;
  transition: all 0.2s ease;
  gap: 8px;
  font-size: 14px;
  color: #303133;
}

.menu-item:hover {
  background: #f5f7fa;
}

.menu-divider {
  height: 1px;
  background: #e4e7ed;
  margin: 4px 0;
}

.context-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  z-index: 1999;
}

/* 语音识别状态 */
.voice-recognition {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  display: flex;
  align-items: center;
  justify-content: center;
  background: rgba(0, 0, 0, 0.6);
  backdrop-filter: blur(10px);
  z-index: 3000;
}

.voice-panel {
  background: white;
  padding: 40px;
  border-radius: 16px;
  box-shadow: 0 20px 60px rgba(0, 0, 0, 0.3);
  text-align: center;
  min-width: 400px;
}

.voice-animation {
  display: flex;
  justify-content: center;
  gap: 6px;
  margin-bottom: 24px;
}

.voice-wave {
  width: 6px;
  height: 20px;
  background: linear-gradient(180deg, #409eff 0%, #66b1ff 100%);
  border-radius: 3px;
  animation: voiceWave 1s ease-in-out infinite;
}

.voice-wave:nth-child(1) { animation-delay: 0s; }
.voice-wave:nth-child(2) { animation-delay: 0.15s; }
.voice-wave:nth-child(3) { animation-delay: 0.3s; }
.voice-wave:nth-child(4) { animation-delay: 0.45s; }
.voice-wave:nth-child(5) { animation-delay: 0.6s; }

@keyframes voiceWave {
  0%, 100% { height: 15px; opacity: 0.5; }
  50% { height: 50px; opacity: 1; }
}

.voice-text {
  font-size: 18px;
  font-weight: 500;
  color: #303133;
  margin-bottom: 8px;
  min-height: 28px;
}

.voice-hint {
  font-size: 13px;
  color: #909399;
  margin-bottom: 16px;
}

/* 语音面板动画 */
.voice-panel-enter-active,
.voice-panel-leave-active {
  transition: all 0.3s ease;
}

.voice-panel-enter-from {
  opacity: 0;
  transform: scale(0.9);
}

.voice-panel-leave-to {
  opacity: 0;
  transform: scale(0.9);
}

/* AI帮助内容 */
.ai-help-content {
  padding: 16px 0;
}

.help-section {
  margin-bottom: 20px;
}

.help-section h4 {
  margin: 0 0 12px 0;
  font-size: 16px;
  font-weight: 600;
  color: #303133;
}

.help-section ul {
  margin: 0;
  padding-left: 20px;
}

.help-section li {
  margin-bottom: 8px;
  line-height: 1.5;
  color: #606266;
}

.help-section strong {
  color: #303133;
}

/* 动画 */
.chat-panel-enter-active,
.chat-panel-leave-active {
  transition: all 0.3s ease;
}

.chat-panel-enter-from {
  opacity: 0;
  transform: translateY(20px) scale(0.95);
}

.chat-panel-leave-to {
  opacity: 0;
  transform: translateY(20px) scale(0.95);
}

.quick-actions-enter-active,
.quick-actions-leave-active {
  transition: all 0.3s ease;
}

.quick-actions-enter-from {
  opacity: 0;
  transform: translateY(20px);
}

.quick-actions-leave-to {
  opacity: 0;
  transform: translateY(20px);
}

.page-fade-enter-active,
.page-fade-leave-active {
  transition: all 0.3s ease;
}

.page-fade-enter-from {
  opacity: 0;
  transform: translateY(10px);
}

.page-fade-leave-to {
  opacity: 0;
  transform: translateY(-10px);
}

/* 响应式 */
@media (max-width: 768px) {
  .chat-panel {
    width: calc(100vw - 40px) !important;
    height: calc(100vh - 40px) !important;
    right: 20px !important;
    bottom: 20px !important;
  }
  
  .quick-actions-panel {
    width: calc(100vw - 40px);
    right: 20px;
  }
  
  .smart-search {
    width: 200px;
  }
  
  .ai-avatar {
    bottom: 20px;
    right: 20px;
  }
}
</style>
